package cn.edu.zafu.bigdata.liuwenyi;
import java.net.*;
import java.util.Scanner;

public class UDPClient {
    public static void main(String[] args) {
        String serverHost = "192.168.16.20"; // 服务端地址（同学电脑 IP）
        int serverPort = 2702;         // 服务端端口

        try (DatagramSocket socket = new DatagramSocket();
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("已启动客户端，连接到服务端：" + serverHost + ":" + serverPort);

            while (true) {
                System.out.print("输入 'time' 请求当前时间，或输入 'exit' 退出: ");
                String input = scanner.nextLine();

                if ("exit".equalsIgnoreCase(input)) {
                    System.out.println("退出客户端");
                    break;
                }

                if ("time".equalsIgnoreCase(input)) {
                    byte[] requestBytes = input.getBytes();
                    InetAddress serverAddress = InetAddress.getByName(serverHost);

                    // 发送请求数据包
                    DatagramPacket requestPacket = new DatagramPacket(requestBytes, requestBytes.length, serverAddress, serverPort);
                    socket.send(requestPacket);

                    // 接收服务端响应数据包
                    byte[] responseBuffer = new byte[1024];
                    DatagramPacket responsePacket = new DatagramPacket(responseBuffer, responseBuffer.length);
                    socket.receive(responsePacket);

                    // 显示服务端返回的时间
                    String serverTime = new String(responsePacket.getData(), 0, responsePacket.getLength());
                    System.out.println("服务端时间：" + serverTime);
                } else {
                    System.out.println("无效指令，请输入 'time' 或 'exit'");
                }
            }
        } catch (Exception e) {
            System.err.println("客户端发生错误：" + e.getMessage());
        }
    }
}
